package com.gonsin.gview.logic.websocket;


import com.gonsin.gview.logic.services.GViewClientServiceImpl;
import com.gonsin.gview.logic.utils.SpringUtil;
import com.gonsin.gview.logic.websocket.message.GViewMessage;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;

@Slf4j
@Component
@ServerEndpoint("/gview/websocket")
public class GWebSocketSession {


    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        GViewClientServiceImpl clientService = SpringUtil.getBean(GViewClientServiceImpl.class);
        clientService.channelActive(session);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        GViewClientServiceImpl clientService = SpringUtil.getBean(GViewClientServiceImpl.class);
        clientService.channelInactive(session);
    }

    /**
     * 收到客户端消息后调用的方法
     * @param text
     * 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String text, Session session) {
        GViewMessage message = new Gson().fromJson(text, GViewMessage.class);
        GViewClientServiceImpl clientService = SpringUtil.getBean(GViewClientServiceImpl.class);
        clientService.channelRead(session, message);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误", error);
    }

}
